from fastapi import APIRouter, Query, Path, Body,Request
from sqlalchemy.orm import Session
from models import ResponseModel,ResponseList
from schemas import CommentBase,CommentCreate, ListComment,ItemComment
from curd import create_comment,get_comments,get_comment,del_comments,update_comments
from db import Db
from sqlalchemy.testing.exclusions import succeeds_if
from utils import UserAgent

# 创建一个 APIRouter 实例
router = APIRouter(
	prefix='/comments',
	tags=['/comments 评论模块']
)

@router.post('/create',summary="新增评论",response_model=ResponseModel[ItemComment])
async def add_comment(
		request: Request,
		comment: CommentCreate = Body(..., description="新增评论信息"),
		db: Session = Db
):
	mach = UserAgent( request)
	# 使用 ip 作为用户id - 这里需要转换为整数或者使用其他方式
	# comment.user_id = mach['ip_address']  # 原来的代码
	comment.user_id = None  # 暂时设为None，因为IP地址不能直接转换为整数
	comment.extradata = mach['device_info']
	res = create_comment(db=db, comment=comment)
	if res:
		return ResponseModel.success(data=res)
	else:
		return ResponseModel.error(code=401,message="新增失败")


@router.post('/list',summary="查询评论数据列表")
def list_comment(comment: ListComment, db: Session = Db):
	db_data = get_comments(db=db, comment=comment)
	if db_data:
		return db_data
	elif not db_data:
		return ResponseList.error(code=401,message="没有数据")

@router.get('/comment-query',summary="参数查询评论数据",response_model=ResponseModel[ItemComment])
def find_query(
		id: int = Query(..., description="id"),
		db: Session = Db
):
	item_data = get_comment(db=db,id=id)
	return ResponseModel(data=item_data)
	# return item_data



@router.get('/comment/{id}',summary="路径查询评论数据",response_model=ResponseModel[ItemComment])
def find_comment(
		id: int = Path(..., description="查询评论数据id"),
		db: Session = Db
):
	item_data = get_comment(db=db,id=id)
	return ResponseModel(data=item_data)
	
@router.delete('/del/{id}',summary="删除数据")
def del_comment(
		id: int = Path(..., description="评论数据id"),
		db: Session = Db
):
	item_data = del_comments(db=db,id=id)
	return item_data

@router.patch('/update',summary="更新数据")
def patch_comment(
		el: ItemComment = Body(..., description="更新数据"),
		db: Session = Db
):
	item_data = update_comments(db=db,el=el)
	return item_data

